<?php

class InvoiceHeadersController extends AppController {
	
	var $uses = array('InvoiceHeader','InvoiceItem');

	public function index( $page = null ) {
		
		$this->pageTitle = 'Invoice Listing';
		
		//This will setup default query conditions
		$conditions = array(
				'contain' => false,
    			'order' => array('entry_date ASC', 'InvoiceHeader.id ASC'),
    	);

		//This will get current user 
		$curruser = $this->Session->read('User');

		//If not a superuser, listing will only be for his organization
		if ( $curruser['User']['access_level'] > 0 ) {
			$conditions['conditions']['Organization.id'] = $curruser['User']['organization_id'];
		}

		//If not an admin, listing will only be for his deparment and division		
		//if ( $curruser['User']['access_level'] > 1 ) {
		//	$conditions['conditions']['Department.id'] = $curruser['User']['department_id'];
		//	$conditions['conditions']['Division.id'] = $curruser['User']['division_id'];
		//}
		
		$conditions['conditions']['InvoiceHeader.status'] = 'A';


		$invoiceHeaders = $this->InvoiceHeader->find('all', 
			$conditions);
		
		//pr($invoiceHeaders);
		
		$this->set('invoiceHeaders', $invoiceHeaders);
		
		/*
		$running_balance = 0;
		
		function updatebalance(&$value, $key) {
			global $running_balance;
					
			if ( $value['Ledger']['type'] == 'D') {
				$running_balance = $running_balance - $value['Ledger']['amount'];
			} elseif ( $value['Ledger']['type'] == 'C' ) {
				$running_balance = $running_balance + $value['Ledger']['amount'];
			}
			
			$value['Ledger']['balance'] = $running_balance;
						
		}
		
		array_walk($invoiceHeaders, "updatebalance");
		
		$page_offset 	= 25;
		$page_numbr 	= ($page == null ? 1 : $page);
		$page_total 	= ( count($invoiceHeaders) ) / $page_offset;

		if ( $page_numbr <= $page_total ) {
			$invoiceHeaders = array_slice($invoiceHeaders, -($page_numbr * $page_offset), $page_offset);
			
		} else {
			$invoiceHeaders = array_slice($invoiceHeaders, -($page_numbr * $page_offset), $page_offset - (($page_numbr * $page_offset) - count($invoiceHeaders)));

		}
		
		$pages['current'] = $page_numbr;
		$pages['total'] = ceil($page_total);
		$pages['linked_page'] = array(
									'controller' => 'ledgers', 
									'action' => 'index'
									);
		$filter = 1;
		$sidebarRight = 1;
		$this->set('pages', $pages);
		$this->set('filter', $filter);
		$this->set('sidebarRight', $sidebarRight);		
		*/
		
		
	}

	function add(){
		
		$user = $this->Session->read('User');
		
		$this->loadModel('Term');
		$terms = $this->Term->find('list', array('conditions' => array('organization_id' => array(0, $user['User']['organization_id']))));
			
		if ( $this->request->is('post') ) {
			
			try {
				
				$this->InvoiceHeader->begin();
				$this->InvoiceItem->begin();
				$this->InvoiceHeader->set('organization_id', $user['User']['organization_id']);
								
				if	($this->InvoiceHeader->save( $this->request->data ) ) {
					
					$InvoiceHeaderID = $this->InvoiceHeader->id;
	
					foreach($this->data['InvoiceItem'] as $v) {
						$this->request->data['InvoiceItem']['invoice_header_id'] = $InvoiceHeaderID;
						$this->request->data['InvoiceItem']['item_id'] = $v['item_id'];
						$this->request->data['InvoiceItem']['qty'] = $v['qty'];
						$this->request->data['InvoiceItem']['unit_price'] = $v['unit_price'];
						
						$this->loadModel('InvoiceItem');
						$this->InvoiceItem->create();
						$this->InvoiceItem->save( $this->request->data );
						
					}
	
				}
				
				$this->InvoiceHeader->commit();
				$this->InvoiceItem->commit();

			} catch (Exception $e) {

				$this->InvoiceHeader->rollback();
				$this->InvoiceItem->rollback();
				
				echo 'Caught exception: ',  $e->getMessage(), "\n";
				//pr($this->data['InvoiceItem']);
				
			}
		
		}

		$this->set('terms',	$terms);

	}

	function getCustomers() 
	{
		$term = $_GET['term'];
		$this->layout = null ;
		
		$curruser = $this->Session->read('User');
		
		$this->loadModel('Customer');
		$customers = $this->Customer->find('all', array(
												'fields' => array('id', 'name as label', 'notes'), 
												'conditions'=>array(
													'organization_id' => $curruser['User']['organization_id'],
													'name LIKE' => '%' . $term . '%'
													)
												)
		);
		
		$data = array();

		foreach( $customers as $customer) {
			array_push($data, $customer['Customer']);
		}

 		$this->set('json_data', $data);
    	$this->render('/Elements/ajaxreturn'); // This View is declared at /Elements/ajaxreturn.ctp
		
		
	}

	function getItems() 
	{
		$term = $_GET['term'];
		$this->layout = null ;
		
		$curruser = $this->Session->read('User');
		
		$this->loadModel('Item');
		$items = $this->Item->find('all', array(
												'fields' => array('id', 'name as label', 'price'), 
												'conditions'=>array(
													'organization_id' => $curruser['User']['organization_id'],
													'name LIKE' => '%' . $term . '%'
													)
												)
		);
		
		$data = array();

		foreach( $items as $item) {
			array_push($data, $item['Item']);
		}

 		$this->set('json_data', $data);
    	$this->render('/Elements/ajaxreturn'); // This View is declared at /Elements/ajaxreturn.ctp
		
		
	}

	function getCustomerDiscount() {

		$this->layout = null ;
		
		//$curruser = $this->Session->read('User');
		
		$customer = $_POST['customer'];
		$item = $_POST['item'];	
		
		$this->loadModel('CustomerItem');
		$discounts = $this->CustomerItem->find('all', array(
												//'fields' => array('discount'), 
												'conditions'=>array(
													'customer_id' 	=> $customer,
													'item_id'		=> $item
													)
												)
		);
		
		//$discount = $customer + $item; // + 10.12;
		//$discount = 10;
		
		if ( count($discounts) != 0 ) {
			//foreach( $discounts as $discount) {
				//array_push($data, $item['Item']);
				$data = array( "discount" => $discounts[0]['CustomerItem']['discount'] );
			//	}
			} else {
				$data = array( "discount" => 0);
				
			}
		//$data = array( "discount" => $discount[0]['discount']);
		
 		$this->set('json_data', $data);
    	$this->render('/Elements/ajaxreturn'); // This View is declared at /Elements/ajaxreturn.ctp

	}
	
	function beforeRender() {
		parent::beforeRender();
		$this->set('module', 'Invoice');
	}
	
}

?>